import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import {
  Breadcrumb,
  Card,
  Form,
  Button,
  Space,
  Radio,
  Input,
  Select,
  Upload,
  Modal,
  message,
} from 'antd'
import { getChannels } from '../../api/channels'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import styles from './ArticlePublish.module.scss'
import { PlusOutlined } from '@ant-design/icons'
import { baseURL } from 'utills/request'
import { addArticle, getArticleInfo, reviseArticle } from 'api/article'

const { Option } = Select

export default class ArticlePublish extends Component {
  state = {
    channels: [],
    //文章的封面类型
    type: 1,
    //用于控制上传的图片以及图片的显示
    fileList: [],
    showPreview: false,
    previewURL: '',
    isUpload: true,
    // isRevise: !!this.props.match.params.id,
    id: this.props.match.params.id,
  }
  formRef = React.createRef()
  componentDidMount() {
    this.getChannelsList()
    if (this.state.id) {
      this.getArticleById(this.state.id)
    }
  }
  async getChannelsList() {
    const res = await getChannels()
    this.setState({
      channels: res.data.channels,
    })
  }
  //封装获取文章详情函数
  async getArticleById(id) {
    const res = await getArticleInfo(id)
    // console.log(res)
    const value = {
      ...res.data,
      type: res.data.cover.type,
    }
    this.formRef.current.setFieldsValue(value)
    this.setState({
      type: res.data.cover.type,
      fileList: res.data.cover.images.map((item) => {
        return { url: item }
      }),
    })
  }
  changeType = (e) => {
    // console.log(e)
    this.setState({
      type: e.target.value,
    })
    if (e.target.value === 0) {
      this.setState({
        fileList: [],
      })
    } else if (e.target.value === 1) {
      if (this.state.fileList.length > 1) {
        this.setState({
          fileList: this.state.fileList.filter((_, i) => i === 0),
        })
      }
    }
  }
  uploadImg = (e) => {
    // console.log(e)
    if (this.state.isUpload) {
      this.setState({
        fileList: e.fileList,
      })
    } else {
      this.setState({
        isUpload: true,
      })
    }
  }

  handlePreview = (file) => {
    // console.log(file.response.data.url)
    const imgURL = file.url || file.response.data.url
    this.setState({
      showPreview: true,
      previewURL: imgURL,
    })
  }
  handleCancel = () => {
    this.setState({
      showPreview: false,
      previewURL: '',
    })
  }
  beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'

    if (!isJpgOrPng) {
      message.error('你只能上传PNG或是JPG格式的图片!')
      this.setState({
        isUpload: false,
      })
      return false
    }

    const isLt1M = file.size / 1024 / 1024 < 1

    if (!isLt1M) {
      message.error('图片大于1MB!')
      this.setState({
        isUpload: false,
      })
      return false
    }

    return isJpgOrPng && isLt1M
  }
  //封装一个save方法用于提交表单
  async save(value, draft) {
    if (this.state.type !== this.state.fileList.length) {
      message.warn('上传图片数量不准确！')
      return
    }
    //const imgURL = value.image.file.url || value.image.file.response.data.url
    const imgURL = this.state.fileList.map((item) => {
      return item.url || item.response.data.url
    })

    /* 
    console.log(
      imgURL,
      this.state.type,
      value.title,
      value.content,
      value.channel_id
    ) 
    */

    const data = {
      title: value.title,
      content: value.content,
      channel_id: value.channel_id,
      cover: {
        type: this.state.type,
        images: imgURL,
      },
    }
    // console.log(data)
    if (this.state.id) {
      await reviseArticle(this.state.id, draft, data)
      message.success('修改成功', 0.8)
    } else {
      await addArticle(data, draft)
      message.success('添加成功', 0.8)
    }
    this.props.history.push('/home/list')
  }
  onFinish = async (value) => {
    this.save(value, false)
  }
  addDraft = async () => {
    const value = await this.formRef.current.validateFields()
    console.log('表单的值', value)
    this.save(value, true)
  }

  render() {
    // console.log(this.props.match.params.id)
    return (
      <div className={styles.ArticlePublish}>
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {this.state.id ? '编辑文章' : '发布文章'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            ref={this.formRef}
            labelCol={{ span: 4 }}
            size="large"
            onFinish={this.onFinish}
            validateTrigger={['onChange', 'onBlur']}
            initialValues={{
              content: '',
              type: 1,
            }}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: '标题不能为空',
                },
              ]}
            >
              <Input
                autoComplete="off"
                style={{ width: 400 }}
                placeholder="请输入标题"
              ></Input>
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[
                {
                  required: true,
                  message: '请选择频道',
                },
              ]}
            >
              <Select
                placeholder="请选择文章频道"
                style={{
                  width: 400,
                }}
              >
                {this.state.channels.map((item) => {
                  return (
                    <Option value={item.id} key={item.id}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </Form.Item>
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              {this.state.type !== 0 && (
                <Upload
                  listType="picture-card"
                  name="image"
                  action={`${baseURL}/v1_0/upload`}
                  fileList={this.state.fileList}
                  onChange={this.uploadImg}
                  onPreview={this.handlePreview}
                  beforeUpload={this.beforeUpload}
                >
                  {this.state.fileList.length < this.state.type && (
                    <PlusOutlined />
                  )}
                </Upload>
              )}
            </Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[
                {
                  required: true,
                  message: '请选择频道',
                },
              ]}
            >
              <ReactQuill
                theme="snow"
                placeholder="请输入文章内容..."
              ></ReactQuill>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  {this.state.id ? '确认修改' : '发布文章'}
                </Button>
                <Button size="large" type="primary" onClick={this.addDraft}>
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
        <Modal
          visible={this.state.showPreview}
          onCancel={this.handleCancel}
          title="图片预览"
          footer={null}
        >
          <img
            alt="example"
            style={{ width: '100%' }}
            src={this.state.previewURL}
          />
        </Modal>
      </div>
    )
  }
}
